from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from marshmallow import Schema,fields

app = Flask(__name__)

ma = Marshmallow()
ma.init_app(app)

class User(object):
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.created_at = datetime.now()
        self.friends = []
        self.books = []

class Book(object):
    def __init__(self, title, author):
        self.title = title
        self.author = author  # 用来代替MySQL中的外键关系

class BookSchema(Schema):
    title = fields.String()
    # 使用lambda匿名函数，使只有在使用author时才会找UserSchema对象，不然可能出现先后调用，导致对象找不到的情况出现
    # 用来序列化外键对象，可以将外键对象按照指定的格式进行序列化，并且外键指定的格式可以完成任何支持的marshmallow操作
    author = fields.Nested(lambda: UserSchema())

class UserSchema(Schema):
    name = fields.String()
    email = fields.Email()
    created_at = fields.DateTime(format='%Y-%m-%d %H:%H:%S')
    # 双向嵌套，例如找出所有属于该用户的所有书籍。注意：在大数据量时，数据返回将非常慢
    books = fields.List(fields.Nested(BookSchema(exclude=("author",)))) #exclude表示排除字段
    # books = fields.List(fields.Nested(lambda: BookSchema(only=("title",))))

@app.route("/")
def index():
    #一对多或多对多
    user0 = User(name="南派三叔", email="sanshu@163.com")
    book1 = Book(title="盗墓笔记1", author=user0)
    book2 = Book(title="盗墓笔记2", author=user0)
    user0.books = [book1, book2]
    us = UserSchema()
    user_data = us.dump(user0)
    print(user_data)
    """
    打印结果：
            {
                'books': 
                    [
                        {'title': '盗墓笔记1'}, 
                        {'title': '盗墓笔记2'}
                    ], 
                'name': '南派三叔', 
                'created_at': '2021-03-05 23:23:54', 
                'email': 'sanshu@163.com'
            }
    """
    user1 = User(name="天下霸唱", email="sanshu@163.com")
    book3 = Book(title="鬼吹灯",author=user1)
    book4 = Book(title="鬼吹灯1",author=user1)
    user1.books = [book3, book4]
    user_list = [user0,user1]

    us = UserSchema()
    user_data = us.dump(user_list, many= True)
    print(user_data)

    """
    打印效果：
    [
        {
            'created_at': '2021-03-05 23:23:55','email': 'sanshu@163.com','name': '南派三叔',
            'books': 
                [
                    {'title': '盗墓笔记1'}, 
                    {'title': '盗墓笔记2'}
                ]
        },
        {
            'created_at': '2021-03-05 23:23:55','email': 'sanshu@163.com','name': '天下霸唱', 
             'books': 
                [
                    {'title': '鬼吹灯'}, 
                    {'title': '鬼吹灯1'}
                ]
        }
    ]
    
    """

    return "hello"

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0" , port=5998)
